package com.sandberg.shopper;

import com.sandberg.shopper.core.HelpScreen;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.Secure;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

// For licensing
import com.android.vending.licensing.LicenseChecker;
import com.android.vending.licensing.LicenseCheckerCallback;
import com.android.vending.licensing.ServerManagedPolicy;
import com.android.vending.licensing.AESObfuscator;


public class ShopperActivity extends Activity {

	private final int DIALOG_HELP = 1;
	private final int DIALOG_ERROR = 2;

	// For licensing
	private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqqq4dWA+qJuiN56GOYyWSkOQ+hQGmKTrfXv0A4hbSi4MTqQfSzqRtgrzsc1AoScF0TaLmNjjVM4vfBS61hSYI4EgqUbWW8hxUerJBeVo/QB/zpbCyhRo28ADm7lKFHrxrwKphm5/LIkc0I1ZFBUDuqtRrVklAm08kSfARtegEmcp6ZT/v0l4Al1EUENehx440GtYGCKFQrRRaGLLWqxrKqJurquUWc8L2Sy4rBnthexW+Ku08B+EP84ytG3PyC5EqdvPTJwdRBmqWIUiQUe/NgxkVpKCN4JMRNRhheDGViA6MVKmFHkY6PihAFftTV2XSGD01yP5HZ9GETGJA6yUfQIDAQAB";

    // 20 random bytes for obfustration.
    private static final byte[] SALT = new byte[] {-45, 55, 35, -125, -105, -55, 75, -65, 55, 85, -95, -45, 75, -115, -35, -115, -15, 35, -65, 85};

    private LicenseCheckerCallback mLicenseCheckerCallback;
    private LicenseChecker mChecker;
    // A handler on the UI thread.
    private Handler mHandler;
    private String mErrorString = null;

    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		// Licensing
        mHandler = new Handler();

        // Try to use more data here. ANDROID_ID is a single point of attack.
        String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);

        // Library calls this when it's done.
        mLicenseCheckerCallback = new MyLicenseCheckerCallback();
        // Construct the LicenseChecker with a policy.
        mChecker = new LicenseChecker(
            this, new ServerManagedPolicy(this,
                new AESObfuscator(SALT, getPackageName(), deviceId)),
            BASE64_PUBLIC_KEY);
        mChecker.checkAccess(mLicenseCheckerCallback);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mChecker.onDestroy();
    }

	public void myClickHandler(View target) {
		if (target.getId() == R.id.buttonPercent) {
			Intent intent = new Intent(this, ShopperPercentActivity.class);
			startActivity(intent);
		}
		else if (target.getId() == R.id.buttonPerPiece) {
			Intent intent = new Intent(this, ShopperPieceActivity.class);
			startActivity(intent);
		}
		else if (target.getId() == R.id.buttonCheapest) {
			Intent intent = new Intent(this, ShopperCheapestActivity.class);
			startActivity(intent);
		}
    }

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
	    Dialog dialog = null;
	    switch(id) {
	    	case DIALOG_HELP:
	    		// do the work to define the pause Dialog
	    		dialog = HelpScreen.createHelpScreen(this, R.string.help_shopper);
	    		break;
	    	case DIALOG_ERROR:
	    		// Show error to user
	    		dialog = HelpScreen.createHelpScreen(this, mErrorString);
	    		break;
	    }
	    return dialog;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		menu.add(getResources().getString(R.string.option_menu_options))
			.setIcon(android.R.drawable.ic_menu_preferences)
			.setIntent(new Intent(this, ShopperSettingsActivity.class));

		menu.add(getResources().getString(R.string.option_menu_about))
			.setIcon(android.R.drawable.ic_menu_info_details)
			.setIntent(new Intent(this, ShopperAboutActivity.class));

		menu.add(getResources().getString(R.string.option_menu_help))
			.setIcon(android.R.drawable.ic_menu_help);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		String title = (String) item.getTitle();
		if (title.compareTo(getResources().getString(R.string.option_menu_help)) == 0) {
			showDialog(DIALOG_HELP);
			return true;
		}
		return false;
	}

	/* Temp method for debugging */
    private void displayResult(final String text) {
        mHandler.post(new Runnable() {
            public void run() {
            	mErrorString = text;
        		showDialog(DIALOG_ERROR);
            }
        });
    }

    // Licensing code
    private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
    	public void allow() {
    		if (isFinishing()) {
    			// Don't update UI if Activity is finishing.
    			return;
    		}
    		// Allow user access.
    	}
    	
    	public void dontAllow() {
    		if (isFinishing()) {
    			// Don't update UI if Activity is finishing.
    			return;
    		}
    		// Application not licenced
    		displayResult(getResources().getString(R.string.app_licence_error));
    	}

    	public void applicationError(ApplicationErrorCode errorCode) {
            if (isFinishing()) {
                // Don't update UI if Activity is finishing.
                return;
            }
            // This is a polite way of saying the developer made a mistake
            // while setting up or calling the license checker library.
            // Please examine the error code and fix the error.
            final String errorString = String.format(getString(R.string.app_error), errorCode);
            displayResult(errorString);
        }
    }
}
